
<template>
  <div class="app-container">
    <el-card>
      <div slot="header">
        <span>生成视频</span>
      </div>
      
      <div v-if="documentInfo">
        <el-descriptions title="文档信息" :column="2" border>
          <el-descriptions-item label="文档标题">{{ documentInfo.title }}</el-descriptions-item>
          <el-descriptions-item label="文档类型">{{ documentInfo.fileType }}</el-descriptions-item>
          <el-descriptions-item label="文件大小">{{ formatFileSize(documentInfo.fileSize) }}</el-descriptions-item>
          <el-descriptions-item label="上传时间">{{ documentInfo.createTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <el-divider></el-divider>
      
      <el-form ref="generateForm" :model="generateForm" :rules="rules" label-width="120px">
        <el-form-item label="选择音色" prop="voiceType">
          <el-radio-group v-model="generateForm.voiceType">
            <el-radio label="zh-CN-XiaoxiaoNeural">晓晓（女声）</el-radio>
            <el-radio label="zh-CN-YunxiNeural">云希（男声）</el-radio>
            <el-radio label="zh-CN-YunjianNeural">云健（男声）</el-radio>
            <el-radio label="zh-CN-XiaoyiNeural">晓艺（女声）</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="语速" prop="speechRate">
          <el-slider
            v-model="generateForm.speechRate"
            :min="0.5"
            :max="2"
            :step="0.1"
            show-input
            :show-input-controls="false"
          >
          </el-slider>
          <div class="slider-tips">建议语速：0.8-1.2</div>
        </el-form-item>
        
        <el-form-item label="音调" prop="pitch">
          <el-slider
            v-model="generateForm.pitch"
            :min="0.5"
            :max="2"
            :step="0.1"
            show-input
            :show-input-controls="false"
          >
          </el-slider>
          <div class="slider-tips">建议音调：0.8-1.2</div>
        </el-form-item>
        
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="generateForm.title" placeholder="请输入视频标题" />
        </el-form-item>
        
        <el-form-item label="视频描述" prop="description">
          <el-input
            v-model="generateForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入视频描述（可选）"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="startGenerate" :loading="loading">
            开始生成
          </el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 生成进度 -->
      <div v-if="showProgress" class="progress-container">
        <el-divider></el-divider>
        <h4>生成进度</h4>
        <el-progress
          :percentage="progress"
          :status="progressStatus"
          :stroke-width="20"
          :text-inside="true"
        ></el-progress>
        <div class="progress-text">{{ progressText }}</div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getDocumentById } from '@/api/document'
import { generateVideo, getVideoProgress } from '@/api/video'

export default {
  name: 'VideoGenerate',
  data() {
    return {
      documentId: this.$route.params.id,
      documentInfo: null,
      generateForm: {
        voiceType: 'zh-CN-XiaoxiaoNeural',
        speechRate: 1.0,
        pitch: 1.0,
        title: '',
        description: ''
      },
      rules: {
        voiceType: [
          { required: true, message: '请选择音色', trigger: 'change' }
        ],
        speechRate: [
          { required: true, message: '请设置语速', trigger: 'change' }
        ],
        pitch: [
          { required: true, message: '请设置音调', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入视频标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ]
      },
      loading: false,
      showProgress: false,
      progress: 0,
      progressStatus: null,
      progressText: '',
      progressTimer: null,
      videoId: null
    }
  },
  created() {
    this.loadDocumentInfo()
  },
  beforeDestroy() {
    if (this.progressTimer) {
      clearInterval(this.progressTimer)
    }
  },
  methods: {
    loadDocumentInfo() {
      getDocumentById(this.documentId).then(response => {
        this.documentInfo = response.data
        this.generateForm.title = this.documentInfo.title + ' - 视频版'
      })
    },
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    startGenerate() {
      this.$refs.generateForm.validate(valid => {
        if (valid) {
          this.loading = true
          const data = {
            documentId: this.documentId,
            ...this.generateForm
          }
          
          generateVideo(data).then(response => {
            this.videoId = response.data
            this.showProgress = true
            this.startProgressCheck()
            this.$message.success('视频生成任务已提交，请稍候...')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    startProgressCheck() {
      this.progressTimer = setInterval(() => {
        this.checkProgress()
      }, 2000)
    },
    checkProgress() {
      if (!this.videoId) return
      
      getVideoProgress(this.videoId).then(response => {
        const progress = response.data
        this.progress = progress.percentage
        this.progressText = progress.message
        
        if (progress.status === 'completed') {
          this.progressStatus = 'success'
          this.progressText = '视频生成完成！'
          if (this.progressTimer) {
            clearInterval(this.progressTimer)
          }
          this.$message.success('视频生成成功！')
          setTimeout(() => {
            this.$router.push(`/video/preview/${this.videoId}`)
          }, 2000)
        } else if (progress.status === 'failed') {
          this.progressStatus = 'exception'
          this.progressText = '视频生成失败：' + progress.message
          if (this.progressTimer) {
            clearInterval(this.progressTimer)
          }
          this.loading = false
        }
      }).catch(() => {
        if (this.progressTimer) {
          clearInterval(this.progressTimer)
        }
        this.loading = false
      })
    },
    goBack() {
      this.$router.push('/document/list')
    }
  }
}
</script>

<style lang="scss" scoped>
.progress-container {
  margin-top: 30px;
  text-align: center;
}

.progress-text {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.slider-tips {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>
